package com.storage.web.controller.system;

import com.storage.common.annotation.Log;
import com.storage.common.config.Global;
import com.storage.common.core.controller.BaseController;
import com.storage.common.core.domain.AjaxResult;
import com.storage.common.core.domain.ServiceResponse;
import com.storage.common.core.page.TableDataInfo;
import com.storage.common.enums.BusinessType;
import com.storage.common.utils.file.FileUploadUtils;
import com.storage.framework.web.OperationContext;
import com.storage.framework.web.enums.RequestOperation;
import com.storage.system.domain.StorageGoods;
import com.storage.system.domain.StorageImage;
import com.storage.system.domain.StorageProduct;
import com.storage.system.service.IStorageProductService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;

/**
 * 产品 信息操作处理
 *
 * @author ruoyi
 * @date 2019-08-26
 */
@Api(tags = "产品相关接口")
@RestController
public class StorageProductController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StorageProductController.class);

    @Autowired
    private IStorageProductService storageProductService;

    /**
     * 查询产品列表
     */
    @ApiOperation(value = "查询产品列表")
    @GetMapping("/system/product/{product_id}")
    @ResponseBody
    public StorageProduct getProduct(@PathVariable("product_id") Long productId) {
        return storageProductService.selectStorageProductById(productId);
    }

    /**
     * 查询产品列表
     */
    @ApiOperation(value = "查询产品列表")
    @GetMapping("/system/product/list")
    @ResponseBody
    public TableDataInfo list(@RequestOperation OperationContext context,
                              StorageProduct storageProduct,
                              Integer pageNum,
                              Integer pageSize,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date startDate,
                              @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") Date endDate) {
        if (startDate != null) {
            storageProduct.setStartTime(startDate);
        }
        if (endDate != null) {
            storageProduct.setEndTime(endDate);
        }
        ServiceResponse<TableDataInfo> response = storageProductService.selectStorageProductList(context.getStorageUser(), storageProduct, pageNum, pageSize);
        return response.getData();
    }

    /**
     * 查询代理商产品列表
     *
     * @param agentUserId
     * @return
     */
    @ApiOperation(value = "查询代理商产品列表")
    @GetMapping("/system/product/agent/list")
    @ResponseBody
    public TableDataInfo agentList(@RequestOperation OperationContext context,
                                   @RequestParam(value = "agentUserId") Long agentUserId,
                                   @RequestParam(value = "productType", required = false) Integer productType,
                                   @RequestParam(value = "brandName", required = false) String brandName,
                                   @RequestParam(value = "categoryName", required = false) String categoryName,
                                   @RequestParam(value = "pageNum", required = false) Integer pageNum,
                                   @RequestParam(value = "pageSize", required = false) Integer pageSize) {

        StorageProduct storageProduct = new StorageProduct();
        storageProduct.setCreateUserId(agentUserId);
        storageProduct.setNewProduct(productType);
        storageProduct.setBrandName(brandName);
        storageProduct.setCategoryName(categoryName);
        ServiceResponse<TableDataInfo> response = storageProductService.selectAgentProductList(context.getStorageUser(), storageProduct, pageNum, pageSize);
        return response.getData();
    }

    /**
     * 修改保存产品
     *
     * @param products
     * @return
     */
    @ApiOperation(value = "修改保存产品")
    @Log(title = "修改保存产品", businessType = BusinessType.UPDATE)
    @PostMapping("/system/product/save")
    @ResponseBody
    public AjaxResult saveProduct(@RequestOperation OperationContext context,
                                  @RequestBody String products) {
        return storageProductService.updateStorageProduct(context.getStorageUser(), products);
    }

    /**
     * 更新产品状态
     *
     * @param product
     * @return
     */
    @ApiOperation(value = "更新产品状态")
    @Log(title = "更新产品状态", businessType = BusinessType.UPDATE)
    @PostMapping("/system/product/update/status")
    @ResponseBody
    public AjaxResult updateProductStatus(@RequestOperation OperationContext context,
                                          @RequestBody StorageProduct product) {
        return storageProductService.updateProductStatus(context.getStorageUser(), product);
    }

    /**
     * 删除产品
     */
    @ApiOperation(value = "删除产品")
    @Log(title = "删除产品", businessType = BusinessType.DELETE)
    @GetMapping("/system/product/remove")
    @ResponseBody
    public AjaxResult removeProduct(@RequestOperation OperationContext context,
                                    String ids) {
        return storageProductService.deleteStorageProductByIds(context.getStorageUser(), ids);
    }

    /**
     * 修改保存商品(单品)
     */
    @ApiOperation(value = "修改保存商品(单品)")
    @Log(title = "修改保存商品(单品)", businessType = BusinessType.UPDATE)
    @PostMapping("/system/goods/save")
    @ResponseBody
    public AjaxResult editGoodsSave(@RequestOperation OperationContext context,
                                    @RequestBody StorageGoods storageGoods) {
        return storageProductService.updateStorageGoods(context.getStorageUser(), storageGoods);
    }

    /**
     * 删除商品(单品)
     */
    @ApiOperation(value = "删除商品(单品)")
    @Log(title = "删除商品(单品)", businessType = BusinessType.DELETE)
    @GetMapping("/system/goods/remove")
    @ResponseBody
    public AjaxResult removeGoods(@RequestOperation OperationContext context,
                                  String ids) {
        return storageProductService.deleteStorageGoodsByIds(context.getStorageUser(), ids);
    }

    /**
     * 上传商品图片
     */
    @ApiOperation(value = "上传商品图片", notes = "上传商品图片")
    @Log(title = "上传商品图片", businessType = BusinessType.UPDATE)
    @PostMapping("/system/product/upload/image")
    @ResponseBody
    public AjaxResult uploadImage(@RequestOperation OperationContext context,
                                  @RequestParam("file") MultipartFile file) {
        try {
            if (!file.isEmpty()) {
                String path = FileUploadUtils.upload(Global.getAvatarPath(), file);
                String fileName = file.getOriginalFilename();
                String type = fileName.substring(fileName.lastIndexOf(".") + 1);

                StorageImage image = new StorageImage();
                image.setSourceName(fileName);
                image.setUuidName(RandomStringUtils.random(20, true, true));
                image.setPath(path);
                image.setType(type);

                return storageProductService.uploadImage(context.getStorageUser(), image);
            }
            return error();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("上传商品图片！", e);
            return error(e.getMessage());
        }
    }

    /**
     * 在线选货 - 获取对应代理商品牌下拉列表
     */
    @ApiOperation(value = "在线选货 - 获取品牌下拉列表")
    @Log(title = "在线选货 - 获取品牌下拉列表", businessType = BusinessType.OTHER)
    @GetMapping("/system/product/brandValues")
    @ResponseBody
    public AjaxResult getSelectBrandValues(@RequestOperation OperationContext context,
                                           @RequestParam("providerUseId") Long providerUserId) {
        ServiceResponse<List<String>> brandsResponse = storageProductService.getSelectBrandValues(context.getStorageUser(), providerUserId);
        if (!brandsResponse.isSuccess()) {
            return AjaxResult.error(brandsResponse.getError());
        }
        return AjaxResult.success(brandsResponse.getData());
    }

    /**
     * 查询当前商品在代理商管辖的店铺中的销售比例
     */
    @ApiOperation(value = "")
    @Log(title = "查询当前商品在代理商管辖的店铺中的销售比例", businessType = BusinessType.OTHER)
    @GetMapping("/system/product/shop/detail")
    @ResponseBody
    public AjaxResult getProductShopSellDetail(@RequestOperation OperationContext context,
                                               @RequestParam("productSkuCode") String productSkuCode) {
        // 获取当前用户的库存中所有商品的进货价总和、所有单品的颜色总和，商品的货号总和
        ServiceResponse<AjaxResult> response = storageProductService.getProductShopSellDetail(context.getStorageUser(), productSkuCode);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return response.getData();
    }


    /**
     * pc 店铺销售
     */
    @ApiOperation(value = "")
    @Log(title = "查询当前商品在代理商管辖的店铺中的销售比例", businessType = BusinessType.OTHER)
    @GetMapping("/system/product/shop/detail/v2")
    @ResponseBody
    public AjaxResult getProductShopSellDetailV2(@RequestOperation OperationContext context,
                                                 @RequestParam("productSkuCode") String productSkuCode,
                                                 @RequestParam("shopId") Long shopId) {
        // pc 店铺销售
        ServiceResponse<AjaxResult> response = storageProductService.getProductShopSellDetailV2(context.getStorageUser(), productSkuCode, shopId);
        if (!response.isSuccess()) {
            return AjaxResult.error(response.getError());
        }
        return response.getData();
    }
}
